package org.one.afternoon.service.impl;


import jakarta.annotation.Resource;
import org.one.afternoon.config.MinioConfig;
import org.one.afternoon.domain.EdgeData;
import org.one.afternoon.domain.dto.Result2BackDto;
import org.one.afternoon.domain.dto.Swim2BackDto;
import org.one.afternoon.domain.dto.SwimmingDto;
import org.one.afternoon.mapper.EdgeMapper;
import org.one.afternoon.provider.detection_ai.DetectionProvider;
import org.one.afternoon.service.EdgeService;
import org.one.afternoon.utils.MinioUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
public class EdgeServiceImpl implements EdgeService {
    // 创建Logger实例
    private static final Logger logger = LoggerFactory.getLogger(EdgeServiceImpl.class);

    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private MinioConfig minioConfig;

    @Value("${IMAGE_LOCATION:spring.servlet.multipart.location}")
    private String uploadFilePath;

    @Autowired
    private EdgeMapper edgeMapper;

    @Resource
    private DetectionProvider detectionProvider;

    @Override
    public void uploadBucket(InputStream inputStream, String name, String type) {
        try {
            minioUtils.uploadFile(minioConfig.getBucketName(), inputStream, name, type);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @Override
    public void saveImage(String path, String lat, String lon) {
        try {
            saveData2DB(path, lat, lon);
        } catch (Exception e) {
            logger.error("File upload failed: %s".formatted(e.getMessage()));
        }
    }

    @Override
    public String getFileUrl(String filename) {
        return minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(), filename);
    }

    private void saveData2DB(String filePath, String lat, String lon) {
        edgeMapper.insertOne(filePath, lat, lon, new Date());
    }


    @Override
    public List<EdgeData> findNewImage() {
        return edgeMapper.selectNewEdges();
    }

    @Override
    public boolean updateStatus(int id) {
        return edgeMapper.updateById(id);
    }

    @Override
    public Result2BackDto pushImage(Swim2BackDto swim2BackDto) {
        return detectionProvider.pushImage(swim2BackDto);
    }

    @Override
    public SwimmingDto detectObject(String ip, String path) {
        return detectionProvider.detectObject(ip, path);
    }
}
